﻿using DataManageSystem.Data;
using DataManageSystem.Models.LimsModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ToolsController : ControllerBase
    {
        private readonly DeviceDbContext _dbContext;

        public ToolsController(DeviceDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [HttpPost("import-excel")]
        public async Task<IActionResult> ImportExcel(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("文件不能为空");

            var result = new List<TEquipmentEnergyConsume>();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);
                using (var package = new ExcelPackage(stream))
                {
                    var worksheet = package.Workbook.Worksheets[0]; // 读取第一个表
                    int rowCount = worksheet.Dimension.Rows;

                    for (int row = 2; row <= rowCount; row++) // 从第2行开始读（跳过表头）
                    {
                        var code = worksheet.Cells[row, 1].Text.Trim(); // 第1列：设备编码
                        var name = worksheet.Cells[row, 2].Text.Trim(); // 第2列：设备名称
                        var system = worksheet.Cells[row, 5].Text.Trim(); // 第5列：设备系统

                        var dto = new TEquipmentEnergyConsume
                        {
                            Guid = Guid.NewGuid().ToString(),
                            ApiCode = code,
                            EquipmentName = name,
                            EquipmentType = system == "配电系统" ? "电表" : "水表",
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            CreateUser = "lkc",
                            UpdateUser = "lkc",
                            Valid = true,
                            CollectionFrequency = "1",
                            CollectionFrequencyUnit = "天",
                            Flag = "1",
                        };

                        result.Add(dto);
                    }

                    // 保存到数据库
                    _dbContext.TEquipmentEnergyConsumes.AddRange(result);
                    await _dbContext.SaveChangesAsync();
                }
            }

            return Ok(new { message = $"成功导入 {result.Count} 条数据。", data = result });
        }
    }
}
